package com.nalai.market.v1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nalai.market.v1.mapper.UserMapper;
import com.nalai.market.v1.model.User;
import com.nalai.market.v1.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author com.nalai
 * @since 2021-08-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public int userLogin(User user,String rem, HttpServletResponse response, HttpSession session) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        User u = userMapper.selectOne(wrapper);
        if (u != null) {
            if (u.getPassword().equals(user.getPassword())) {
                session.setAttribute("user", u);
                if (rem != null) {//rem 代表记住密码复选框
                    //创建Cookie对象
                    Cookie cookie = new Cookie("username", user.getUsername());
                    Cookie cookie2 = new Cookie("password", user.getPassword());
                    //设置保存时间,单位秒
                    cookie.setMaxAge(60 * 60 * 24 * 30);
                    cookie2.setMaxAge(60 * 60 * 24 * 30);
                    //通过response对象将Cookie下发给客户端
                    response.addCookie(cookie);
                    response.addCookie(cookie2);
                }
                return 1;//登录成功
            } else {
                return 2;//密码错误
            }
        }
        return 0;//用户不存在
    }
}
